{% extends "base.html" %}

{% block title %}苹果设备列表{% end %}

{% block script %}
{% end %}
{% block style %}
<style>
    .color-right {
        background-color: yellowgreen;
        color: white;
    }

    .color-wrong {
        color: red;
    }
</style>
{% end %}

{% block content %}
<div class="container">
    <span onclick="location.reload()">
        <el-alert v-if="websocketDisconnected" title="WebSocket连接断开，点击或F5刷新重连" type="error">
        </el-alert>
    </span>
    <el-table :data="tableData">
        <el-table-column label="Status">
            <template slot-scope="scope">
                <template v-if="!scope.row.present">
                    <span style="color: gray">Offline</span>
                </template>
                <template v-else>
                    <a :href='"/devices/"+scope.row.udid+"/remotecontrol"' target="_blank"
                        @click="clickStatus($event, scope.row)">
                        {{!deviceStatusName(scope.row)}}
                    </a>
                </template>
            </template>
        </el-table-column>
        <el-table-column prop="udid" label="UDID">
            <template slot-scope="scope">
                <template v-if="scope.row.present && scope.row.using && scope.row.userId == user.email">
                    <a :href='"/devices/"+scope.row.udid+"/applecontrol"' target="_blank">{{!scope.row.prop_serial}}</a>
                </template>
                <template v-else>
                    {{!scope.row.prop_serial}}
                </template>
            </template>
        </el-table-column>
        <el-table-column prop="prop_brand" label="Brand"></el-table-column>
        <el-table-column prop="prop_version" label="Version"></el-table-column>
    </el-table>
</div>
{% end %}

{% block script %}
<script>
    const currentUserEmail = "{{ current_user.email }}";
    const currentUserName = "{{ current_user.username }}"
</script>
<script>
    $.getJSON("/devices" + "?json")
        .done((ret) => {
            new Vue({
                el: "#app",
                data: Object.assign({
                    websocketDisconnected: false,
                    user: {
                        name: currentUserName,
                        email: currentUserEmail,
                    },
                    devices: [],
                }, ret.data),
                mounted() {
                    console.log("Mounted:", this.devices)
                },
                computed: {
                    tableData() {
                        return this.filteredDevices.map(v => {
                            for (const key in v.properties) {
                                if (v.properties.hasOwnProperty(key)) {
                                    v['prop_' + key] = v.properties[key]
                                }
                            }
                            let display = v.display || {}
                            v['display_size'] = display.width + "x" + display.height;
                            return v;
                        })
                    },
                    filteredDevices() {
                        return []
                        // return this.devices;
                        return [{
                            udid: "123123124dsfa123423r134123",
                            using: false,
                            present: true, // present is generated by length of sources
                            ready: false,
                            private: false,
                            platform: "apple",
                            owner: "anonymous@domain.com",
                            group: "ntes",
                            address: "10.0.0.123:8100",
                            sources: {
                                "bad1-131jfla-3313131": {
                                    name: "raspberry",
                                    address: "10.0.1.123:8100",
                                    priority: 2,
                                },
                                "7718231-sdljf3lkjsf-sfsdf": {
                                    name: "wifi",
                                    address: "10.45.16.71:7912",
                                    priority: 1
                                }
                            },
                            createdAt: "2018-12-1 12:00:01",
                            lastUsingAt: "2018-12-1 12:00:01",
                            prop_displayWidth: 1080,
                            prop_displayHeight: 1120,
                            properties: {
                                brand: "sumsung",
                                model: "SM-G9209",
                                hwaddr: "90:b6:86:7e:7d:ff",
                                version: "6.0.1",
                                sdk: 23,
                            },
                            ip: "127.0.0.1",
                            display: {
                                height: 2560,
                                width: 1440,
                            },
                        }]
                    }
                },
                filters: {
                    formatTime(value) {
                        var t = moment(value)
                        return t.format("YYYY-M-D HH:mm:ss");
                    },
                    fromNow(value) {
                        return moment(value).fromNow();
                    }
                },
                methods: {
                    formatTimeUsed() {
                        // let duration = moment(this.finishedAt) - moment(this.createdAt);
                        // return moment.utc(duration).format('HH:mm:ss')
                    },
                    deviceAcquire(udid) { // for multi device acquire
                        return $.ajax({
                            method: "post",
                            url: "/api/v1/user/devices",
                            data: JSON.stringify({
                                "udid": udid,
                            }),
                            dataType: "json",
                        })
                            .done(ret => {
                                console.log(ret)
                            })
                    },
                    deviceRelease(udid) {
                        $.ajax({
                            method: "delete",
                            url: "/api/v1/user/devices/" + udid,
                            dataType: "json",
                        })
                            .then(ret => {
                                console.log(ret)
                            })
                    },
                    deviceStatusName(device) {
                        if (!device.present) {
                            return "Offline"
                        }
                        if (!device.using) {
                            return "Use"
                        }
                        if (device.userId == currentUserEmail) {
                            return "Stop"
                        }
                        return "Busy"
                    },
                    clickStatus(event, device) {
                        let status = this.deviceStatusName(device)
                        console.log("Status", status)
                        switch (status) {
                            case "Use":
                                return true;
                            case "Stop":
                                this.deviceRelease(device.udid);
                                event.preventDefault()
                                return true
                            default:
                                event.preventDefault()
                        }
                        console.log(device.udid)
                    }
                },
                mounted() {
                    let scheme = location.protocol === 'https' ? 'wss' : 'ws';
                    let wsURL = scheme + "://" + location.host + "/websocket/devicechanges?platform=apple";
                    let ws = new WebSocket(wsURL);
                    ws.onopen = (evt) => {
                        console.log("Websocket Connected")
                    }
                    ws.onmessage = (evt) => {
                        let m = JSON.parse(evt.data);
                        switch (m.event) {
                            case "update":
                                this.devices = this.devices.map((v) => {
                                    console.log(v.udid)
                                    if (v.udid == m.data.udid) {
                                        return m.data
                                    }
                                    return v
                                })
                                console.log("Updated:", this.devices)
                                break;
                            case "insert":
                                this.devices.unshift(m.data);
                                break;
                            default:
                                console.error("Unknown event type", m.event)
                                break;
                        }
                    }
                    ws.onclose = (evt) => {
                        console.log("Websocket closed")
                        this.websocketDisconnected = true
                    }
                }
            })
        })
</script>
{% end %}